<template>
    <div class="m16">
        <a-row :gutter="5">
            <a-col :span="6">
                <BasicTree ref="treeRef" title="组织机构" toolbar search :treeData="treeData" :expandedKeys="expandedKeys"
                    :showLine="true" :autoExpandParent="true" showIcon @select="handleSelect" />
            </a-col>
            <a-col :span="18">
                <a-card>
                    <Alert class="mb20" message="点击左侧组织机构树查看详细信息，此时可以修改或删除组织机构信息。再次点击取消选中时，可以新增组织机构信息。" banner></Alert>
                    <BasicForm @register="registerForm" />
                    <div class="center">
                        <a-button v-auth="Permission.ADD" :loading="formLoading" type="primary" @click="handleSubmit"> 保存
                        </a-button>
                        <a-button v-auth="Permission.DEL" :loading="formLoading" class="m16" color="error"
                            @click="handleDelete"> 删除 </a-button>
                        <a-button :loading="formLoading" @click="handleReset"> 重置 </a-button>
                    </div>
                </a-card>
            </a-col>
        </a-row>
    </div>
</template>
<script lang="ts" setup>
import { onBeforeMount, ref } from 'vue';
import { BasicTree } from '/@/components/Tree';
import { BasicForm, useForm } from '/@/components/Form/index';
import { formSchema, Permission } from './index-option';
import { getOrgTreeApi, saveOrgApi, updateOrgApi, getOrgDetailApi, delOrgApi } from '/@/api/sys/org';
import { OrgSearchModel, OrgVOModel } from '/@/api/sys/model/orgModel';
import { useMessage } from '/@/hooks/web/useMessage';
import SysConstant from "/@/constant/sysConstant";
import { Alert } from 'ant-design-vue';

const orgId = ref('');
const expandedKeys = ref([]);
const params: OrgSearchModel = {};
const formLoading = ref(false);
const selectedOrg = ref<OrgVOModel>({});

const { createMessage, createConfirm } = useMessage();

const treeData = ref([]);
onBeforeMount(() => {
    getTreeData();
});

async function getTreeData() {
    let result = await getOrgTreeApi(params);
    treeData.value = result.data || [];
    expandedKeys.value = result.data.map(item => item.key);
    updateSchema({
        field: 'parentId',
        componentProps: { treeData: treeData.value },
    });
}

// 选中事件
async function handleSelect(selectedKeys) {
    if (selectedKeys.length > 0) {
        orgId.value = selectedKeys[0];
        let result = await getOrgDetailApi(orgId.value);
        selectedOrg.value = result.data;
        if (selectedOrg.value.parentId == SysConstant.TREE_TOP_ID) {
            selectedOrg.value.parentId = '';
        }
        setFieldsValue({
            ...selectedOrg.value,
        });
    } else {
        selectedOrg.value = {};
        resetFields();
    }
}

const [registerForm, { resetFields, validate, updateSchema, setFieldsValue }] = useForm({
    labelWidth: 140,
    schemas: formSchema,
    showActionButtonGroup: false,
    baseColProps: { lg: 24, md: 24 },
});

async function handleSubmit() {
    let res;
    try {
        const values = await validate();
        formLoading.value = true;
        if (selectedOrg.value.orgId) {
            const param = { ...values, orgId: selectedOrg.value.orgId };
            res = await updateOrgApi(param);
        } else {
            const param = { ...values };
            res = await saveOrgApi(param);
        }
        createMessage.success(res.msg);
    } finally {
        formLoading.value = false;
        if (res.success) {
            getTreeData();
            if (selectedOrg.value.orgId) {
                let result = await getOrgDetailApi(orgId.value);
                selectedOrg.value = result.data;
                if (selectedOrg.value.parentId == SysConstant.TREE_TOP_ID) {
                    selectedOrg.value.parentId = '';
                }
                setFieldsValue({
                    ...selectedOrg.value,
                });
            } else {
                resetFields();
            }
        }
    }
}

function handleDelete() {
    if (selectedOrg.value.orgId) {
        createConfirm({
            iconType: 'warning',
            title: '确认提示',
            content: '请确认是否删除组织机构【' + selectedOrg.value.name + '】？',
            onOk: () => {
                formLoading.value = true;
                delOrgApi([selectedOrg.value.orgId!]).then(res => {
                    createMessage.success(res.msg);
                    getTreeData();
                    resetFields();
                    selectedOrg.value = {};
                }).finally(() => {
                    formLoading.value = false;
                })
            }
        });
    } else {
        createMessage.warning('请选择左侧的组织机构');
    }

}

function handleReset() {
    resetFields();
    setFieldsValue({
        ...selectedOrg.value,
    });
}

</script>
  
<style lang="less" scoped>
.m16 {
    margin: 16px;
}

.mb20 {
    margin-bottom: 20px;
}

.center {
    text-align: center;
}
</style>